package com.acce.gxsc.page.supervisionReport.list;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.acce.gxsc.R;
import com.acce.gxsc.common.App;
import com.acce.gxsc.common.DateUtils;
import com.acce.gxsc.common.Tools;
import com.acce.gxsc.model.netBean.NetSupervisionDutyBean;
import com.acce.gxsc.page.supervisionReport.supervisionReportPresenter.SupervisionReportActivity;
import com.acce.sdk.BaseActivity;
import com.acce.sdk.User;
import com.acce.sdk.base.mvp.BaseMvpFragment;
import com.acce.sdk.utils.ToastUtils;
import com.acce.sdk.widget.adapterlv.CommonAdapter;
import com.acce.sdk.widget.adapterlv.ViewHolder;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/9/22.
 */

public class SupervisionReportListFragment extends BaseMvpFragment<SupervisionReportListView, SupervisionReportListPresenter> implements SupervisionReportListView {

    String maxDate;
    View rootView;
    LayoutInflater mInflater;
    CommonAdapter mAdapter;
    List<NetSupervisionDutyBean> mData;
    /**
     * 需要查询的日期
     **/
    int[] mCurrentDate;
    @Bind(R.id.supervision_report_list)
    ListView mListView;
    @Bind(R.id.tv_date)
    TextView mDateTime;

    public static SupervisionReportListFragment newInstance() {
        Bundle args = new Bundle();
        SupervisionReportListFragment fragment = new SupervisionReportListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_supervision_report_list, container, false);
        ButterKnife.bind(this, rootView);
        init();
        setHasOptionsMenu(true);
        mPresenter.loadDataList(mDateTime.getText().toString());
        return rootView;
    }

    private void init() {
        mCurrentDate = DateUtils.getCurrentDates();
        mData = new ArrayList<>();
        mInflater = LayoutInflater.from(getActivity());
        maxDate = String.format("%02d-%02d-%02d", mCurrentDate[0], mCurrentDate[1], mCurrentDate[2]);
        mDateTime.setText(maxDate);
        mPresenter.currentOnTime(mDateTime.getText().toString());
        mListView.setAdapter(mAdapter = new CommonAdapter<NetSupervisionDutyBean>(getContext(), R.layout.supervision_report_listview_item, mData) {
            @Override
            protected void convert(ViewHolder viewHolder, NetSupervisionDutyBean data, int i) {
                viewHolder.setText(R.id.tv_column_a, Tools.getDutyString(data.columnA, data.columnB));
                viewHolder.setText(R.id.tv_column_c, Tools.getString(data.columnC));
                viewHolder.setText(R.id.tv_total_a, Tools.getString(data.totalA));
                viewHolder.setText(R.id.tv_total_b, Tools.getString(data.totalB));
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String dutyId = mData.get(position).columnA;
                Intent intent = new Intent(getActivity(), SupervisionReportActivity.class);
                intent.putExtra("dutyId", dutyId);
                getActivity().startActivity(intent);
            }
        });
    }

    @OnClick({R.id.iv_minus_day, R.id.iv_add_day, R.id.iv_select_date, R.id.tv_date, R.id.btn_print})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_minus_day:
                minusDay();
                mPresenter.currentOnTime(mDateTime.getText().toString());
                break;
            case R.id.iv_add_day:
                addDay();
                mPresenter.currentOnTime(mDateTime.getText().toString());
                break;
            case R.id.iv_select_date:
            case R.id.tv_date:
                selectDate();
                mPresenter.currentOnTime(mDateTime.getText().toString());
                break;
            case R.id.btn_print:
                printOrder();
                break;
        }
    }
    ScrollView sRootView;
    private void printOrder() {
        sRootView= (ScrollView) mInflater.inflate(R.layout.supervision_report_list_dialog_print, (ViewGroup) getActivity().findViewById(R.id.dialog));
      //  final LinearLayout llContent = ButterKnife.findById(rootView, R.id.ll_content);
        final TextView tvClasses = ButterKnife.findById(sRootView, R.id.tv_classes);
        final TextView tvTollCollector = ButterKnife.findById(sRootView, R.id.tv_toll_collector);
        final TextView tvDate = ButterKnife.findById(sRootView, R.id.tv_date);
        final LinearLayout llChild = ButterKnife.findById(sRootView, R.id.ll_child);
        tvClasses.setText(MessageFormat.format("班次：{0}",App.currentOnTime));
        tvTollCollector.setText(MessageFormat.format("操作员：{0}", User.getInstance().getRealName()));
        tvDate.setText(DateUtils.getTime1());
        llChild.removeAllViews();
        for (int i = 0; i < mData.size(); i++) {
            NetSupervisionDutyBean dutyBean = mData.get(i);
            View llDuty = mInflater.inflate(R.layout.supervision_report_list_dialog_print_item_duty, llChild, false);
            final TextView tvColumnA = ButterKnife.findById(llDuty, R.id.tv_column_a);
            final TextView tvColumnC = ButterKnife.findById(llDuty, R.id.tv_column_c);
            final TextView tvTotalA = ButterKnife.findById(llDuty, R.id.tv_total_a);
            final TextView tvTotalB = ButterKnife.findById(llDuty, R.id.tv_total_b);
            tvColumnA.setText(Tools.getDutyString(dutyBean.columnA, dutyBean.columnB));
            tvColumnC.setText(Tools.getString(dutyBean.columnC));
            tvTotalA.setText(Tools.getString(dutyBean.totalA));
            tvTotalB.setText(Tools.getString(dutyBean.totalB));
            llChild.addView(llDuty);
        }
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        final AlertDialog alertDialog = builder
                .setView(sRootView)
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mPresenter.printOrder(sRootView);
                    }
                }).create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    private void minusDay() {
        String date = mDateTime.getText().toString();
        mDateTime.setText(DateUtils.minusDay(date, "yyyy-MM-dd"));
        mPresenter.loadDataList(mDateTime.getText().toString());
    }

    private void addDay() {
        String date = mDateTime.getText().toString();
        if (date.equals(maxDate)) {
            ToastUtils.show("不能超过日期范围");
            return;
        }
        mDateTime.setText(DateUtils.addDay(date, "yyyy-MM-dd"));
        mPresenter.loadDataList(mDateTime.getText().toString());
    }

    private void selectDate() {
        DatePickerDialog dialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                mDateTime.setText(String.format("%02d-%02d-%02d", year, monthOfYear + 1, dayOfMonth));
                mPresenter.loadDataList(mDateTime.getText().toString());
            }
        }, mCurrentDate[0], mCurrentDate[1], mCurrentDate[2]);
        dialog.getDatePicker().setMinDate(new GregorianCalendar(2015, 11, 1).getTimeInMillis());
        dialog.getDatePicker().setMaxDate(new GregorianCalendar(mCurrentDate[0], mCurrentDate[1] - 1, mCurrentDate[2]).getTimeInMillis());
        dialog.setTitle("请选择日期");
        dialog.show();
    }

    @Override
    public void showProgressDialog(String s, boolean b) {
        ((BaseActivity) getActivity()).showProgressDialog(s, b);
    }

    @Override
    public void hideProgressDialog() {
        ((BaseActivity) getActivity()).hideProgressDialog();
    }

    @Override
    public void loadSupervisionReportListSuccess(ArrayList<NetSupervisionDutyBean> data) {
        mData.clear();
        mData.addAll(data);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @Override
    protected SupervisionReportListPresenter createPresenter() {
        return new SupervisionReportListPresenter();

    }
}
